package com.geek.gkpush.groovy;

import com.geek.gkpush.framework.dispatch.SpringCtxUtils;
import com.geek.gkpush.framework.groovy.UniversalExecRunnable;
import com.geek.gkpush.util.excp.ExcpStackUtils;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;

public class AdjustThreadPoolAction implements UniversalExecRunnable {

    @Override
    public Object exec(List<String> args) {
        Map<String, Object> map = new LinkedHashMap<>();
        try {
            // 修改核心线程数
            ThreadPoolExecutor poolExecutor = (ThreadPoolExecutor) SpringCtxUtils.getBean("defaultEventMsgExecutor");
            map.put("修改核心线程数-before", poolExecutor.getCorePoolSize());
            poolExecutor.setCorePoolSize(2);
            map.put("修改核心线程数-after", poolExecutor.getCorePoolSize());

            // 修改最大线程数
            map.put("修改最大线程数-before", poolExecutor.getMaximumPoolSize());
            poolExecutor.setMaximumPoolSize(2);
            map.put("修改最大线程数-after", poolExecutor.getMaximumPoolSize());

            // 修改队列容量上限值
            BlockingQueue<Runnable> queue = poolExecutor.getQueue();
            if (queue instanceof LinkedBlockingQueue) {
                Field capacityField = ReflectionUtils.findField(LinkedBlockingQueue.class, "capacity");
                ReflectionUtils.makeAccessible(capacityField);

                map.put("修改最大队列容量-before", capacityField.get(queue));
                capacityField.set(queue, 1024);
                map.put("修改最大队列容量-after", capacityField.get(queue));
            }
        } catch (IllegalAccessException e) {
            map.put("未知异常", ExcpStackUtils.getStackTrace(e));
        }

        return map;
    }
}